package growth.net.peer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ListeningService implements Runnable {

    private boolean stop = false;
    public static int portNum;
    public static InetAddress ip;
    DatagramSocket listeningSocket;
    RequestProcessor requestProcessor = new RequestProcessor();

    public ListeningService() throws UnknownHostException {
        this.setupSocket();
        ListeningService.ip = InetAddress.getLocalHost();
    }

    public void stopListening() {
        this.stop = true;
    }

    private void setupSocket() throws UnknownHostException {
        this.portNum = (int) (Math.random() * 9999) + 1000;
        if ((portNum > 9999) && (portNum < 1000)) {
            this.setupSocket();
        }
        try {
            this.listeningSocket = new DatagramSocket(this.portNum,
                    InetAddress.getLocalHost());
        } catch (SocketException e) {
            System.out.println("Port: " + portNum
                    + " already taken, trying one more");
            setupSocket();
        }
        System.out.println("Listening on PORT: " + portNum);
    }

    @Override
    public void run() {
        String receivedMsg = null;
        DatagramPacket receivePacket = null;
        byte[] receiveData = null;
        while (!stop) {
            try {
                receiveData = new byte[1024];
                receivePacket = new DatagramPacket(receiveData, receiveData.length);
                listeningSocket.receive(receivePacket);
                receivedMsg = new String(receivePacket.getData());
                requestProcessor.processMessage(receivedMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        listeningSocket.close();
        System.out.println("Socket closed");
    }
}
